﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Security.Claims;

namespace Eqwww.Domain
{
    public class ModelHandler : IModelHandler
    {
        private IHttpContextAccessor _httpContextAccessor;

        public ModelHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string OperatorId()
        {
            if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
            {
                var claim = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
                if (claim != null)
                    return claim.Value;
            }
            return null;
                
        }

        public void Create(ICreateAudited createAudited)
        {
            createAudited.Id = System.Guid.NewGuid().ToString();
            createAudited.CreateTime = DateTime.Now;
            createAudited.CreateUserId = OperatorId();
        }

        public void Update(ILastUpdateAudited lastUpdateAudited)
        {
            lastUpdateAudited.LastUpdateTime = DateTime.Now;
            lastUpdateAudited.LastUpdateUserId = OperatorId();
        }

        public void Delete(IDeleteAudited deleteAudited)
        {
            deleteAudited.DeleteMark = true;
            deleteAudited.DeleteTime = DateTime.Now;
            deleteAudited.DeleteUserId = OperatorId();
        }
    }
}
